package com.dianrui.operation.util;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.util.Util;
import com.dianrui.operation.R;

import java.io.File;
import java.math.BigDecimal;


/**
 * Created by lzy on 2017/11/3.
 * 简单的Glide封装
 */
public class GlideUtil {
    private volatile static GlideUtil instance;

    public static GlideUtil getInstance(){
        if (instance == null){
            synchronized (GlideUtil.class){
                if (instance == null){
                    instance = new GlideUtil();
                }
            }
        }
        return instance;
    }

    /**
     * Glide特点
     * 使用简单
     * 可配置度高，自适应程度高
     * 支持常见图片格式 Jpg png gif webp
     * 支持多种数据源  网络、本地、资源、Assets 等
     * 高效缓存策略    支持Memory和Disk图片缓存 默认Bitmap格式采用RGB_565内存使用至少减少一半
     * 生命周期集成   根据Activity/Fragment生命周期自动管理请求
     * 高效处理Bitmap  使用Bitmap Pool使Bitmap复用，主动调用recycle回收需要回收的Bitmap，减小系统回收压力
     * 这里默认支持Context，Glide支持Context,Activity,Fragment，FragmentActivity
     */
    //默认加载
    public static void loadImageView(Context mContext, String path, ImageView mImageView) {
        if (Util.isOnMainThread()) {
            Glide.with(mContext).asBitmap().load(path).into(mImageView);
        }

    }

    //加载圆形图片
    public  static  void loadUserImageViewSize(Context mContext, String path, ImageView mImageView) {
        if (Util.isOnMainThread()) {
            Glide.with(mContext)
                    .load(path)
                    .apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(500))).into(mImageView);
        }
    }


    /**
     * 加载本地资源图片
     *
     * @param isCircle
     * @param imageView
     * @param context
     * @param resourceId
     */
    public static ImageView glideLoad(boolean isCircle, final ImageView imageView, final Context context, int resourceId) {
        if (context == null) {
            return null;
        }
        if (isCircle) {
            RequestOptions options = new RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .priorityOf(Priority.HIGH)
                    .skipMemoryCache(true);
            Glide.with(context).load((String) imageView.getTag(R.id.glide_tag)).thumbnail(0.7f).apply(options).into(imageView);
        } else {
            RequestOptions options = new RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .priorityOf(Priority.HIGH)
                    .skipMemoryCache(true);
            Glide.with(context)
                    .load(resourceId)
                    .thumbnail(0.7f)
                    .apply(options)
                    .into(imageView);
        }

        return imageView;
    }

    //GLIDE框架下载图片
    public static ImageView downLoader(boolean isCircle, final ImageView imageView, final Context context) {
        if (context == null) {
            return null;
        }


        if (isCircle) {
            RequestOptions options = new RequestOptions().diskCacheStrategy(DiskCacheStrategy.RESOURCE).priorityOf(Priority.NORMAL).skipMemoryCache(true)
                    .transforms(new RoundedCorners(5));

            Glide.with(context).load((String) imageView.getTag(R.id.glide_tag)).thumbnail(0.7f).apply(options).into(imageView);
        } else {
            RequestOptions options = new RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL).priorityOf(Priority.NORMAL).skipMemoryCache(true);
            Glide.with(context.getApplicationContext()).load((String) imageView.getTag(R.id.glide_tag)).apply(options).into(imageView);
        }

        return imageView;
    }

    /**
     * 清理视图内的图片
     *
     * @param view
     */
    public static void clearImg(Context mContext,View view) {
        if (view != null) {
            Glide.get(mContext).clearMemory();
        }
    }

    //清理磁盘缓存
    public  void GuideClearDiskCache(Context mContext) {
        //理磁盘缓存 需要在子线程中执行
        Glide.get(mContext).clearDiskCache();
    }

    //清理内存缓存
    public  void GuideClearMemory(Context mContext) {
        //清理内存缓存  可以在UI主线程中进行
        Glide.get(mContext).clearMemory();
    }

    /**
     * 获取Glide造成的缓存大小
     *
     * @return CacheSize
     */
    public static String getCacheSize(Context context) {
        try {
            return getFormatSize(getFolderSize(new File(context.getCacheDir() + "/" + InternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取指定文件夹内所有文件大小的和
     *
     * @param file file
     * @return size
     * @throws Exception
     */
    public static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (File aFileList : fileList) {
                if (aFileList.isDirectory()) {
                    size = size + getFolderSize(aFileList);
                } else {
                    size = size + aFileList.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }


    /**
     * 格式化单位
     *
     * @param size size
     * @return size
     */
    private static String getFormatSize(double size) {

        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "Byte";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);

        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }


    /**
     * 清除图片磁盘缓存
     */
    public static void clearImageDiskCache(final Context context, final ClearListener clearListener) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.get(context).clearDiskCache();
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (clearListener != null) {
                                    clearListener.onSuccess();
                                }
                            }
                        });
                    }
                }).start();
            } else {
                Glide.get(context).clearDiskCache();
                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (clearListener != null) {
                            clearListener.onSuccess();
                        }
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
            new Activity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (clearListener != null) {
                        clearListener.onFailure();
                    }
                }
            });
            Glide.get(context).clearDiskCache();
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (clearListener != null) {
                        clearListener.onFailure();
                    }
                }
            });

        }
    }

    public interface ClearListener {
        void onSuccess();

        void onFailure();
    }
}
